import { Card, Breadcrumb, Form, Input, Upload, Space, Select } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import "./index.scss";

import toast from "@/components/Toast/toast";

import "react-quill/dist/quill.snow.css";
import { useEffect, useState } from "react";
import {
  addChannelAPI,
  getArticleDetailAPI,
  updateArticleAPI,
} from "@/apis/article";
import { useChannel } from "@/hooks/useChannel";

const { Option } = Select;

const Publish = () => {
  // 获取频道
  const { channelList } = useChannel();

  const navigate = useNavigate();

  // 提交表单
  const onFinish = (values) => {
    console.log(values);
    // 校验封面类型和图片数量是否一致
    if (imageList.length !== Number(type)) {
      // return alert("封面图片数量和封面类型不一致");
      return toast("封面图片数量和封面类型不一致", "error");
    }
    const reqData = {
      title: values.title,
      content: values.content,
      cover: {
        type: Number(type),
        images: imageList.map((item) => {
          if (item.response) {
            return item.response.data.url;
          } else {
            return item.url;
          }
        }),
      },
      channel_id: values.channel_id,
    };
    if (articleId) {
      updateArticleAPI({ ...reqData, id: articleId }).then(() => {
        toast("修改成功", "success");
        window.history.go(-1);
      });
    } else {
      addChannelAPI(reqData).then(() => {
        toast("发布成功", "success");
        navigate("/article");
      });
    }
  };

  // 上传回调
  const [imageList, setImageList] = useState([]);
  const onChange = (info) => {
    console.log(info);
    setImageList(info.fileList);
  };

  // 单选按钮
  const [type, setType] = useState("1");
  const onTypeChange = (e) => {
    console.log(e.target.value);
    setType(e.target.value);
  };

  // 回填数据
  const [searchParams] = useSearchParams();
  const articleId = searchParams.get("id");
  const [form] = Form.useForm();
  useEffect(() => {
    if (articleId) {
      console.log(articleId, "======================");
      const getDetail = async () => {
        const res = await getArticleDetailAPI(articleId);
        console.log(res.data);
        form.setFieldsValue({
          ...res.data,
        });
        setType(res.data.cover.type.toString());
        setImageList(res.data.cover.images.map((item) => ({ url: item })));
      };
      getDetail();
    }
  }, [articleId, form]);

  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb
            items={[
              { title: <Link to={"/"}>首页</Link> },
              { title: `${articleId ? "编辑" : "发布"}文章` },
            ]}
          />
        }
      >
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1 }}
          onFinish={onFinish}
          form={form}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: "请输入文章标题" }]}
          >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: "请选择文章频道" }]}
          >
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {channelList.map((item) => {
                return (
                  <Option key={item.id} value={item.id}>
                    {item.name}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item name="type">
              <input
                type="radio"
                id="single"
                name="imageOption"
                value="1"
                onChange={onTypeChange}
                checked={type === "1"}
              />
              <label htmlFor="single">单图</label>

              <input
                type="radio"
                id="triple"
                name="imageOption"
                value="3"
                onChange={onTypeChange}
                checked={type === "3"}
              />
              <label htmlFor="triple">三图</label>

              <input
                type="radio"
                id="none"
                name="imageOption"
                value="0"
                onChange={onTypeChange}
                checked={type === "0"}
              />
              <label htmlFor="none">无图</label>
            </Form.Item>
            {type !== "0" && (
              <Upload
                listType="picture-card"
                showUploadList
                name="image"
                action={"https://geek.itheima.net/v1_0/upload"}
                maxCount={Number(type)}
                onChange={onChange}
                fileList={imageList}
              >
                <div style={{ marginTop: 8 }}>
                  <PlusOutlined />
                </div>
              </Upload>
            )}
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: "请输入文章内容" }]}
          >
            {/*<ReactQuill
              className="publish-quill"
              theme="snow"
              placeholder="请输入文章内容"
            />*/}
            <Input.TextArea
              placeholder="请输入文章内容"
              className="publish-quill"
              style={{ height: 300 }}
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <button>发布文章</button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Publish;
